<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="状态" prop="state">
        <el-select v-model="queryParams.state" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.c_online_service_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['camp:service:add']"
        >新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="serviceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="客服消息Id" align="center" prop="messageId" />
      <el-table-column label="发送人Id" align="center" prop="senderId" />
      <el-table-column label="接收人Id" align="center" prop="receiverId" />
      <el-table-column label="内容" align="center" prop="content" />
      <el-table-column label="时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="state">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.c_online_service_status" :value="scope.row.state"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['camp:service:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['camp:service:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改在线客服消息表对话框 -->
    <el-dialog title="WebSocket 聊天框" :visible.sync="chatopen" width="500px" append-to-body>
      <el-container class="chatapp">
        <el-header>
          <h1>WebSocket 聊天框</h1>
        </el-header>
        <el-main>
          <el-row :gutter="10" class="mb8">
            <el-col :span="24">
              <el-tabs v-model="activeTab" @tab-click="handleTabClick">
                <el-tab-pane
                  v-for="(chat, index) in chats"
                  :key="chat.userId"
                  :label="chat.userName"
                  :name="chat.userId"
                >
                  <div class="chatbox">
                    <div v-for="(message, index) in chat.messages" :key="index" :class="{'self': message.self}">
                      <span>{{ message.senderUserName }}: </span>{{ message.text }}
                    </div>
                  </div>
                </el-tab-pane>
              </el-tabs>
            </el-col>
          </el-row>
          <el-row :gutter="10" class="mb8">
            <el-col :span="20">
              <el-input v-model="messageInput" placeholder="输入消息..." @keyup.enter="sendMessage"></el-input>
            </el-col>
            <el-col :span="4">
              <el-button type="primary" @click="sendMessage">发送</el-button>
            </el-col>
          </el-row>
        </el-main>
      </el-container>
    </el-dialog>
  </div>
</template>

<script>
import { listService, getService, delService, addService, updateService } from "@/api/camp/service";

import { getToken } from '@/utils/auth'
export default {
  name: "Service",
  dicts: ['c_online_service_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 在线客服消息表表格数据
      serviceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        senderId: null,
        receiverId: null,
        content: null,
        createTime: null,
        state: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        content: [
          { required: true, message: "内容不能为空", trigger: "blur" }
        ],
        createTime: [
          { required: true, message: "时间不能为空", trigger: "blur" }
        ],
        state: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ]
      },
      ws: null,
      messageInput: '',
      chats: [],
      activeTab: '',
      chatopen: false
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询在线客服消息表列表 */
    getList() {
      this.loading = true;
      listService(this.queryParams).then(response => {
        this.serviceList = response.rows;
        // this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        messageId: null,
        senderId: null,
        receiverId: null,
        content: null,
        createTime: null,
        state: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.messageId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.chatopen = true;
      // this.reset();
      // this.open = true;
      // this.title = "添加在线客服消息表";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const messageId = row.messageId || this.ids
      getService(messageId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改在线客服消息表";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.messageId != null) {
            updateService(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addService(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const messageIds = row.messageId || this.ids;
      this.$modal.confirm('是否确认删除在线客服消息表编号为"' + messageIds + '"的数据项？').then(function() {
        return delService(messageIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('camp/service/export', {
        ...this.queryParams
      }, `service_${new Date().getTime()}.xlsx`)
    },
    sendMessage() {
      if (this.messageInput.trim() !== '') {
        //
        const message = {
          sender: 'webUser',
          text: this.messageInput
        };
        // this.ws.send(JSON.stringify(message));
        const activeChat = this.chats.find(chat => chat.userId === this.activeTab);
        var rUserId = (activeChat && activeChat.userId) ? activeChat.userId : "b8c2317c-41c3-4c42-a0bc-dde11a8aa95e";
        this.ws.send(rUserId + ":" + this.messageInput);
        if (activeChat) {
          activeChat.messages.push({ ...message, self: true });
        }
        this.messageInput = '';
        this.scrollToBottom();
      }
    },
    scrollToBottom() {
      this.$nextTick(() => {
        // const chatbox = this.$el.querySelector('.chatbox');
        // chatbox.scrollTop = chatbox.scrollHeight;
      });
    },
    handleTabClick(tab) {
      this.activeTab = tab.name;
    },
    addChat(userId, userName) {
      if (!this.chats.find(chat => chat.userId === userId)) {
        this.chats.push({ userId, userName, messages: [] });
      }
      this.activeTab = userId;
    }

  },

  mounted() {
    // ws://localhost:8082
    const hostname = window.location.hostname;
    const port = window.location.port || '8082';
    this.ws = new WebSocket(`ws://${hostname}:8082/chat?token=` + getToken());
    // this.ws = new WebSocket(`ws://${hostname}:9150/chat?token=` + getToken());
    this.ws.onmessage = (event) => {
      const data = event.data.split(':');
      const message = {
        senderUserId: data[0],
        senderUserName: data[1],
        text: data.slice(2).join(':'),
        self: false
      };
      this.addChat(message.senderUserId, message.senderUserName);
      const chat = this.chats.find(chat => chat.userId === message.senderUserId);
      if (chat) {
        chat.messages.push(message);
      }
      this.scrollToBottom();
    };
  },
};
</script>
